package gagak.framework.web.handler;

import com.g5.framework.web.context.MvcContextApplicationHolder;
import com.g5.framework.web.param.HandlerMethod;
import com.g5.framework.web.utils.ObjectUtils;
import com.g5.framework.web.utils.StringUtils;
import message.Messages;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/*
 * @program: ce
 * @description: requestMapping处理实现
 * @author: houhong
 * @create: 2022-11-23 20:44
 */
public class RequestMappingHandlerMapping extends AbstractHandlerMethodMapping {

    private static String DEFAULT_URL_PREFIX;

    static {

        Messages msgs = Messages.getInstance();
        Properties prop = msgs.getProperties("mvc.properties");
        //初始化扫描路径
        String basePackage = prop.getProperty("mvc.prefix");

        DEFAULT_URL_PREFIX = !StringUtils.isEmpty(basePackage)
                ? basePackage : "/web";
    }

    /*
     * 放在mvc容器里的映射器
     */
    private Map<String, HandlerMethod> handlerMethodMap = new HashMap<String, HandlerMethod>(256);

    /*
     * 获取Mapping
     */
    @Override
    public HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {

        String requestURI = request.getRequestURI();

        if (ObjectUtils.isEmpty(context)) {
            super.initHandlerMethods();
            handlerMethodMap = context.getUrlMappingHandled();
        }
        //真正的url路径
        String realUrlPath = requestURI.substring(requestURI.indexOf(DEFAULT_URL_PREFIX)+DEFAULT_URL_PREFIX.length());

        HandlerMethod handlerMethod = MvcContextApplicationHolder.getMvcApplicationContext().getUrlMappingHandled().get(realUrlPath);
        //// TODO: 2022/11/25  做一些扩展
        return new HandlerExecutionChain(handlerMethod, null);
    }

    public static void main(String[] args) {

        String url = new String("/web/userInfo/all");

        System.out.println(url.indexOf("/userInfo"));
        System.out.println(url.substring(url.indexOf("/userInfo")+"/userInfo".length()));
    }

}